﻿using System.Runtime.InteropServices;

namespace Common
{
    /// <summary>
    /// 键盘控制类
    /// </summary>
    public class InputLanguage
    {
        private const uint KEYEVENTF_EXTENDEDKEY = 0x1;
        private const uint KEYEVENTF_KEYUP = 0x2;

        [DllImport("user32.dll")]
        private static extern short GetKeyState(int nVirtKey);

        [DllImport("user32.dll")]
        private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);

        /// <summary>
        /// 虚拟键枚举
        /// </summary>
        public enum VirtualKeys : byte
        {
            /// <summary>
            /// 数字键锁定
            /// </summary>
            VK_NUMLOCK = 0x90,

            /// <summary>
            /// 滚动锁定
            /// </summary>
            VK_SCROLL = 0x91,

            /// <summary>
            /// 大小写锁定
            /// </summary>
            VK_CAPITAL = 0x14,

            /// <summary>
            /// </summary>
            VK_A = 62
        }

        /// <summary>
        /// 设置按键状态
        /// </summary>
        /// <param name="Key">   </param>
        /// <param name="State"> </param>
        public static void SetState(VirtualKeys Key, bool State)
        {
            if (State != GetState(Key))
            {
                keybd_event((byte)Key, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0);
                keybd_event((byte)Key, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
            }
        }

        /// <summary>
        /// 读取按键状态
        /// </summary>
        /// <param name="Key"> </param>
        /// <returns> </returns>
        public static bool GetState(VirtualKeys Key)
        {
            return (GetKeyState((int)Key) == 1);
        }

        /// <summary>
        /// 开启键盘大写
        /// </summary>
        public static void OpenCAPITAL()
        {
            SetState(VirtualKeys.VK_CAPITAL, true);
        }

        /// <summary>
        /// 关闭键盘大写
        /// </summary>
        public static void CloseCAPITAL()
        {
            SetState(VirtualKeys.VK_CAPITAL, false);
        }

        /// <summary>
        /// 开启键盘滚动锁定
        /// </summary>
        public static void OpenScroll()
        {
            SetState(VirtualKeys.VK_SCROLL, true);
        }

        /// <summary>
        /// 关闭键盘滚动锁定
        /// </summary>
        public static void CloseScroll()
        {
            SetState(VirtualKeys.VK_SCROLL, false);
        }

        /// <summary>
        /// 开启键盘数字锁定键
        /// </summary>
        public static void OpenNum()
        {
            SetState(VirtualKeys.VK_NUMLOCK, true);
        }

        /// <summary>
        /// 关闭键盘数字锁定键
        /// </summary>
        public static void CloseNum()
        {
            SetState(VirtualKeys.VK_NUMLOCK, false);
        }
    }
}